//
//  HYFComposeController.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/27.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class HYFComposeController: UIViewController {
    

    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        setupUI()
    }
    
    private func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
    }
    
    func setupNav(){
        
        //添加控件,添加约束
        view.addSubview(composeTextView)
        composeTextView.addSubview(composePictureView)
        view.addSubview(composeToolBarView)
        
        composeToolBarView.snp_makeConstraints { (make) in
            
            make.height.equalTo(44)
            make.bottom.leading.trailing.equalTo(view)
        }
        
        composePictureView.snp_makeConstraints { (make) in
            
            make.size.equalTo(CGSize(width: SCREENW - 20, height: SCREENW - 20))
            make.top.equalTo(composeTextView).offset(100)
            make.centerX.equalTo(composeTextView)
        }
        
        composeTextView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        composeToolBarView.closure = {[weak self] (type:HYFComposeTabBarViewType)->() in
            
            switch type {
            case .Picture:
                
                self?.selectImage()
            case .Mention:
                print("@")
            case .Trend:
                print("#")
            case .Emotion:
                print("笑脸")
                self?.switchKeyBoard()
                
            case .Add:
                print("+")

            }
        }
        
        //监听键盘将要改变的 frame
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HYFComposeController.ChangeFrameNotification(_:)), name:UIKeyboardWillChangeFrameNotification , object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HYFComposeController.emotionDeleteButton), name: WBEmoticonDeleteButtonNoti, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonButtons:", name: WBemoticonButtonNoti, object: nil)
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imgName: nil, target: self, action: #selector(HYFComposeController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", imgName: nil, target: self, action: #selector(HYFComposeController.sendlAction))
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置导航栏的 view
        navigationItem.titleView = titleView
    }
    
    //表情按钮监听方法
    func emoticonButtons(noti:NSNotification){
        
        //判断是否为nil 而且是否可以转成 emoticon 模型
        guard let emoticon = noti.object as? HYFEmoticon else {
            
         return
        }
        //判断是否为 emoji 表情
        if emoticon.isEmoji {
            
            //十六进制转字符串
            let codeStr = (emoticon.code ?? "" as NSString).emoji()
            
            composeTextView.insertText(codeStr)
        }else {
            
            //代表是图片表情
            //获取当前 composeTextView
            let allAttr = NSMutableAttributedString(attributedString: composeTextView.attributedText)
            
            let lineHeight = composeTextView.font!.lineHeight
            
            let attr = NSAttributedString(emoticon: emoticon, y: -4, lineHeight: lineHeight)
            let selectedRange = composeTextView.selectedRange
            
            //设置富文本属性
            allAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
            
            allAttr.addAttributes([NSFontAttributeName:composeTextView.font!], range: NSRange(location: 0, length: allAttr.length))
            //赋值
            composeTextView.attributedText = allAttr
            
            //重新设置 composeTextView 的选中光标
            composeTextView.selectedRange = NSRange(location: selectedRange.location + 1, length: 0)
            //发送一个通知,告知 textView 隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            //主动调动代理方法,改变右侧按钮的状态
            composeTextView.delegate?.textViewDidChange!(composeTextView)
        }
    }

    //监听方法
    func emotionDeleteButton(){
        
        //删除
        composeTextView.deleteBackward()
    }
    
    //键盘监听方法
    func ChangeFrameNotification(noti:NSNotification){
        
        //判断是否为 nil
        guard let userInfo = noti.userInfo else{
            
            return
        }
        //获取时间
        let duration = userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber
        //通过key 获取 value frame
        let value = userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue
        //获取rect
        let rect = value.CGRectValue()
        
        //更新约束,设置动画
        self.composeToolBarView.snp_updateConstraints { (make) in
            
            make.bottom.equalTo(view).offset(rect.origin.y - SCREENH)
        }
        
        //设置动画
        UIView.animateWithDuration(Double(duration)) { 
            
            self.composeToolBarView.layoutIfNeeded()
        }
    }
    
    deinit{
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: 懒加载表情键盘
    private lazy var emoticonKeyBoardView:HYFEmoticonKeyboardView = HYFEmoticonKeyboardView()
    
    
    //MARK:懒加载控件
    private lazy var titleView:UILabel = {
        
        //用户名字
        let name = HYFUserAccountViewModel.sharedTools.userAccount?.sreen_name ?? ""
        let str = "发微博\n\(name)"
        //获取range
        let range = (str as NSString).rangeOfString(name)
        //创建一个富文本
        let attr = NSMutableAttributedString(string: str)
        //设置富文本
        attr.addAttributes([NSForegroundColorAttributeName:ThemeColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        let label:UILabel = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .Center
        label.attributedText = attr
        
        //设置大小
        label.sizeToFit()
        
        return label
    }()
    
    //懒加载textView
    private lazy var composeTextView:HYFComposeTextView = {
        
        let view = HYFComposeTextView()
        view.delegate = self
        
        view.font = UIFont.systemFontOfSize(16)
        view.placeHolder = "上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博上海三期微博"
        
        // TextView 的滚动方向   总是垂直方向滚动
        view.alwaysBounceVertical = true
        
        return view
    }()
    
    //懒加载 pictureView
    private lazy var composePictureView:HYFComposePictureView = HYFComposePictureView()
    private lazy var composeToolBarView:HYFComposeTabBarView = HYFComposeTabBarView()

    
    func cancelAction(){
        
        //取消第一响应
        composeTextView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: 发布微博
    func sendlAction(){
        print("发布按钮被点击")
//        update()
//        upload()
        
        var allText = ""
        
        //遍历 composeTextView.attributedText
        composeTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0, length: composeTextView.attributedText.length), options: []) { (result, range, _) in
            
            printLog("结果:\(result) 范围:\(range)")
            //代表输入的是 文本附件
            if let att = result["NSAttachment"] as? HYFTextAttachment{
                
                allText += (att.emoticon?.chs ?? "")
                
                
            }else{
               //文字
                //字符串 截取
                let str = (self.composeTextView.attributedText.string as NSString).substringWithRange(range)
                
                allText += str
            }
        }
        
        composePictureView.imageList.count > 0 ? upload(allText) : update(allText)
    }
}


extension HYFComposeController:UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = composeTextView.hasText()
    }

    //滚动的时候,取消 textView 的第一响应者
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        composeTextView.resignFirstResponder()
    }
}

extension HYFComposeController{
    
    func selectImage(){
        
        let pickerVc = UIImagePickerController()
        
        //设置代理
        pickerVc.delegate = self
        
        self.presentViewController(pickerVc, animated: true, completion: nil)
    }
    
    //切换键盘
    func switchKeyBoard(){
        
        //如果inputView 为 nil 代表当前为系统键盘
        if composeTextView.inputView == nil  {
            
            composeTextView.inputView = emoticonKeyBoardView
            
            composeToolBarView.isEmoticon = true
            
        }else{
            //当前为 自定义表情键盘
            composeTextView.inputView = nil
            
            composeToolBarView.isEmoticon = false
        }
        
        //刷新 inputViews
        composeTextView.reloadInputViews()
        //设置第一响应者
        composeTextView.becomeFirstResponder()
        
    }
}


extension HYFComposeController:UINavigationControllerDelegate,UIImagePickerControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        composePictureView.addImages(image.getImageScale(600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

extension HYFComposeController{
    
    //发送文字微博
    func update(status:String){
        
        HYFNetworkTools.shardTools.composeUpdate(status, success: { (response) in
            
              SVProgressHUD.showSuccessWithStatus("发布成功")
            }) { (error) in
                
              print(error)
                
              SVProgressHUD.showErrorWithStatus("发布失败")
        }
    
    }
    
    //发送图片微博
    func upload(status:String){
        
        HYFNetworkTools.shardTools.composeUpload(status, imageList: composePictureView.imageList, success: { (response) in
            
            SVProgressHUD.showSuccessWithStatus("发布成功")

            }) { (error) in
                
             SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
}







